window.LS.user = {
    /* State Check */
    checkState: function() {
        $.ajax({
            url: LS.getURL("users/state"),
            type: "GET",
            dataType: "json",
            error: function(xhr) {
                LS.alertbox.showFatal(LS.localized.errorConnectionFatal);
            },
            success: function(response) {
                LS.alertbox.showError(null);
                
                if(response.user) {
                    // launch main app
                    LS.Main.init(response.user.User);
                } else {
                    // show login view
                    LS.user.launchLogin();
                }
            }
        });
    },
    /* Login */
    login: function(e) {
        if(!LS.user.validateLoginForm()) return;
        
        LS.alertbox.showError(null);
        LS.user.lockLoginForm(true);
        
        $.ajax({
            url: LS.getURL("users/login"),
            type: "POST",
            dataType: "json",
            data: LS.user.getLoginFormData(),
            error: function(xhr) {
                that.alertbox.showError(LS.localized.errorConnection);
                that.user.lockRegisterForm(false);
            },
            success: function(response) {
                LS.alertbox.showError(null);
                
                LS.user.lockLoginForm(false);
                
                if(response.user.success) {
                    // do success
                    LS.exitModal();
                    LS.user.checkState();
                } else {
                    LS.alertbox.showError(response.user.errmsg);
                }
            }
        });
    },
    /* Register */
    register: function(e) {
        if(!LS.user.validateRegistrationForm()) return;
        LS.user.lockRegistrationForm(true);
        
        LS.alertbox.showError(null);
        
        $.ajax({
            url: LS.getURL("users/reg"),
            type: "POST",
            dataType: "json",
            data: this.getRegistrationFormData(),
            error: function(xhr) {
                LS.alertbox.showError(LS.localized.errorConnection);
                LS.user.lockRegistrationForm(false);
            },
            success: function(response) {
                LS.alertbox.showError(null);
                
                LS.user.lockRegistrationForm(false);
                
                if(response.user.success) {
                    LS.exitModal();
                    LS.alertbox.showNotification(LS.localized.registrationSuccess);
                } else {
                    LS.alertbox.showError(response.user.errmsg);
                    if(response.user.error) {
                    	LS.user.showRegError(response.user.error);
                    }
                }
            }
        });
    },
    /* Logout */
    logout: function() {
        $.ajax({
            url: LS.getURL("users/logout"),
            type: "GET",
            dataType: "json",
            error: function(xhr) {
                if(LS.Main.onLogout) LS.Main.onLogout();
                LS.alertbox.showFatal(LS.localized.errorConnectionFatal);
            },
            success: function(response) {
                if(LS.Main.onLogout) LS.Main.onLogout();
                LS.alertbox.showError(null);
                
                if(response.user && response.user.success) {
                    window.location.reload();
                    return;
                }
                LS.alertbox.showError(LS.localized.errorConnectionFatal);
            }
        });
    },
    /* UI Register Form */
    showRegError: function(errs) {
        if(errs == null) {
            $('#reg_form div.error').hide();
            return;
        }
        var f = null;
        for(var i in errs) {
            f = $('#reg_form input[name="'+i+'"]');
            if(f.length) {
                var ferr = $('.error', f.parent());
                if(!ferr.length) {
                    ferr = $(document.createElement("div")).addClass("error");
                    f.parent().append(ferr);
                }
                ferr.html(errs[i]);
            }
            ferr.show();
        }
    },
    lockRegistrationForm: function(lock) {
        window.LS.lockForm('#reg_form', lock);
    },
    validateRegistrationForm: function() {
    	window.LS.alertbox.showError(null);
        this.showRegError(null);
        
        var errors = {}, error_count = 0;
                
        for(var field in LS.localized.registrationFormFieldErrors) {
            try {
            	window.LS.checkFormField('#reg_form', field, LS.localized.registrationFormFieldErrors[field]);
            } catch(e) {
                errors[field] = e;
                error_count++;
            }
        }
        
        if($('#reg_form input[name="password"]').val() != $('#reg_form input[name="password_confirm"]').val()) {
            $('#reg_form input[name="password"]').val("");
            $('#reg_form input[name="password_confirm"]').val("");
            errors['password_confirm'] = LS.localized.registrationPasswordConflict;
            error_count++;
        }
        
        if(error_count != 0) {
            this.showRegError(errors);
            return false;
        }
        return true;
    },
    getRegistrationFormData: function() {
        return window.LS.getFormData('#reg_form');
    },
    /* Login */
    launchLogin: function(username) {
        LS.showModal('#login_div', function(){LS.user.activateLogin(username);});
    },
    activateLogin: function() {
        var username = this.getJustRegisteredUsername();
        if(username) {
            $('#login_form input[name="username"]').val(username);
        }
        
        var field_focus = "username";
        if($('#login_form input[name="username"]').val() != "") {
            field_focus = "password";
        }
        $('#login_form input[name="'+field_focus+'"]').focus();
    },
    validateLoginForm: function() {
        try {
            LS.checkFormField("#login_form", "username", "Please input your username.");
            LS.checkFormField("#login_form", "password", "Please input your password.");
        } catch(errmsg) {
            LS.alertbox.showError(errmsg);
            return false;
        }
        return true;
    },
    lockLoginForm: function(lock) {
        LS.lockForm('#login_form', lock);
    },
    getLoginFormData: function() {
        return LS.getFormData('#login_form');
    },
    /* Register */
    launchRegister: function() {
        $('#login_form input[name="username"]').val("");
        $('#reg_form input').each(function() {
            if(this.type == "text" || this.type == "password")
                this.value = "";
        });
        
        LS.showModal('#reg_div', this.activateRegister);
    },
    activateRegister: function() {
        $('#reg_form input[name="username"]').focus();
    },
    getJustRegisteredUsername: function() {
        var username = $('#reg_form input[name="username"]').val();
        return (username != "") ? username : null;
    }
};
